package cn.hrfax.stf.sdk.template;

import lombok.extern.slf4j.Slf4j;

/**
 * Action执行的模板实现类
 *
 * @author yongSen.wang
 * @date 2019/10/18 14:40
 */
@Slf4j
public class ActionTemplateImpl implements ActionTemplate {

    @Override
    public <R, P> R execute(AbstractCallRemoteAction<R, P> action) throws RuntimeException {
        long startTime = System.currentTimeMillis();
        String apiRemoteName = action.getRemoteName();
        String message = "RemoteRemoteName:" + apiRemoteName + ", request:"
                         + (action.getParam() == null ? "" : action.getParam().toString());
        R result = null;
        try {
            //参数校验
            action.checkParams(action.getParam());

            //逻辑执行
            result = action.doAction(action.getParam());

            action.onSuccess();

            return result;
        } catch (RuntimeException e) {
            log.error(message + e.getMessage());
            action.onError();
            throw e;
        } catch (Exception e) {
            log.error(message, e);
            action.onException();
            throw new RuntimeException("remote error " + e.getMessage());
        } finally {
            action.onFinally();
            long useTime = System.currentTimeMillis() - startTime;
            log.info(message + " ,response:" + (result == null ? "" : result.toString())
                     + " ,useTime(ms):" + useTime);
        }
    }

    @Override
    public <R, P> R executeWithoutLog(AbstractCallRemoteAction<R, P> action) throws RuntimeException {
        long startTime = System.currentTimeMillis();
        String apiRemoteName = action.getRemoteName();
        String message = "RemoteRemoteName:" + apiRemoteName;
        R result = null;
        try {
            //参数校验
            action.checkParams(action.getParam());

            //逻辑执行
            result = action.doAction(action.getParam());

            action.onSuccess();

            return result;
        } catch (RuntimeException e) {
            log.error(message + e.getMessage());
            action.onError();
            throw e;
        } catch (Exception e) {
            log.error(message, e);
            action.onException();
            throw new RuntimeException("remote error " + e.getMessage());
        } finally {
            action.onFinally();
            long useTime = System.currentTimeMillis() - startTime;
            log.info(message + " ,response:" + (result == null ? "" : result.toString())
                     + " ,useTime(ms):" + useTime);
        }
    }

}
